﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.WindowsPhoneCloud.Web.Infrastructure
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Microsoft.IdentityModel.Claims;

    public class UserPrivilegesAuthorizationManager : ClaimsAuthorizationManager
    {
        private readonly IEnumerable<IStorageRequestValidator> storageRequestValidators;

        public UserPrivilegesAuthorizationManager()
            : this(new IStorageRequestValidator[] { new QueueRequestValidator(), new TableRequestValidator(), new BlobRequestValidator(), new SqlAzureODataServiceRequestValidator() })
        {
        }

        public UserPrivilegesAuthorizationManager(IEnumerable<IStorageRequestValidator> storageRequestValidators)
        {
            this.storageRequestValidators = storageRequestValidators;
        }

        public override bool CheckAccess(AuthorizationContext context)
        {
            var identity = context.Principal.Identity as IClaimsIdentity;
            if (identity == null || !identity.IsAuthenticated)
            {
                return false;
            }

            var nameIdentifier = identity.Claims.FirstOrDefault(c => c.ClaimType == ClaimTypes.NameIdentifier);
            if (nameIdentifier == null)
            {
                return false;
            }

            var resourceUri = new Uri(context.Resource.First().Value, UriKind.RelativeOrAbsolute);
            foreach (var validator in this.storageRequestValidators)
            {
                if (validator.DoesRequestApply(resourceUri))
                {
                    return validator.ValidateRequest(nameIdentifier.Value, HttpContext.Current.Request);
                }
            }

            return base.CheckAccess(context);
        }
    }
}